package com.suxin.utils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Tang
 * @classname ReTryUtils
 * @description [  ]
 * @date 2022/10/12 21:09
 */
@Slf4j
public class SimpleReTryUtils {

    private final Integer maxReTryCount;
    private Integer currentCount;

    private SimpleReTryUtils(Integer maxReTryCount) {
        this.maxReTryCount = maxReTryCount;
        this.currentCount = 1;
    }

    public static SimpleReTryUtils create(Integer maxReTryCount) {
        return new SimpleReTryUtils(maxReTryCount);
    }

    public void syncDoTry(Runnable runnable) {
        syncTry(runnable, 0);
    }

    private void syncTry(Runnable runnable, int start) {
        while (start < currentCount && currentCount <= maxReTryCount) {
            try {
                runnable.run();
                start++;
            } catch (Exception e) {
                log.info("重试:{}次执行！", this.currentCount);
                this.currentCount++;
                syncTry(runnable, start + 1);
            }
        }
    }

    public static void main(String[] args) {
        final int[] i = {1};
        SimpleReTryUtils reTryUtils = SimpleReTryUtils.create(3);
        reTryUtils.syncDoTry(() -> {
            if (i[0] == 1) {
                i[0] = i[0] + 1;
                throw new RuntimeException("11");
            }
        });
    }

}
